import { http } from '../utils/http'
import { LoginInfo, LoginResult } from '@/types/modules/login'
import router from '@/router'
import { useLoginAccountStoreWithOut } from '@/store/modules/login'
import { createPermissionRouterGuard } from '@/router/guard/permissionGuard'

const loginAccountStore = useLoginAccountStoreWithOut()

export const onLogin = async (data: LoginInfo) => {
  let res = await http.request<LoginResult>('post', '/api/account', {
    data
  })

  if (res.success === true) { 
    loginAccountStore.setUsername(res.name)    
    loginAccountStore.setAvatar(res.avatar)
    loginAccountStore.setQrCode(res.qrCode)
    loginAccountStore.setToken(res.accessToken)    

    await createPermissionRouterGuard(router)
  }
  
  return res;
}

export const getTokenByUid = async (uid: any) => {
  let res = await http.request<LoginResult>('get', `/api/wecom/auth?uid=${uid}`)

  if (res.success === true) {    
    loginAccountStore.setUsername(res.name)
    loginAccountStore.setAvatar(res.avatar)
    loginAccountStore.setQrCode(res.qrCode)
    loginAccountStore.setUserId(uid)
    loginAccountStore.setToken(res.accessToken)
    
    await createPermissionRouterGuard(router);
  }

  return res;
}

export const onRegister = async (data: { account: string; password: string }) => {
  return http.request('post', '/api/account/Register', {
    data
  })
}